<template>
  <ie-page :loading="loading">

    <template #extra>
      <n-space>
        <n-popconfirm :on-positive-click="back">
          <template #trigger>
            <n-button>取消</n-button>
          </template>
          是否取消，当前编写内容不会被保存？
        </n-popconfirm>
        <n-button @click="handleConfirm" type="primary">保存</n-button>
      </n-space>
    </template>

    <div class="ie-form">
      <a-form
        :model="formValue"
        :style="{ width: '640px', margin: '0 auto 36px' }"
        :rules="formRules"
        @submit="handleSubmit"
        layout="vertical"
        size="large"
        ref="formRef"
      >
        <a-form-item field="title" label="事件名称">
          <a-input v-model="formValue.title" placeholder="请输入事件名称..." />
        </a-form-item>
        <a-form-item field="ticket_source_id" label="事件名称">
          <a-radio-group v-model="formValue.ticket_source_id">
            <a-radio
              v-for="option in sourceOptions"
              :key="option.value"
              :value="option.value"
            >{{ option.name }}</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item field="content" label="事件详情">
          <a-textarea
            v-model="formValue.content"
            placeholder="请描述事件详情..."
            allow-clear
            :max-length="1000"
            show-word-limit
            :auto-size="{ minRows: 10, maxRows: 10 }"
          />
        </a-form-item>
        <a-form-item field="create_msg" label="事件备注">
          <a-textarea
            v-model="formValue.create_msg"
            placeholder="可为联系方式等..."
            allow-clear
            :max-length="250"
            show-word-limit
            :auto-size="{ minRows: 4, maxRows: 4 }"
          />
        </a-form-item>
        <a-form-item field="ticket_attachments" label="事件举证">
          <a-upload
            action="/api/upload"
            download
            :headers="headers"
            :accept="accept"
            v-model:file-list="formValue.ticket_attachments"
          />
        </a-form-item>
      </a-form>
    </div>
  </ie-page>
</template>

<script setup>
import { computed, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useNotification } from 'naive-ui'
import { cloneDeep, isNil } from 'lodash-es'
import { useQuery } from 'villus'
import gql from 'graphql-tag'

import { useApi, getHeaders } from '/@/api'
import { TYPE_IMAGE, TYPE_VIDEO } from '/@/model/attachment'

const formRef = ref()
const accept = [...TYPE_IMAGE, ...TYPE_VIDEO].join(',')
const loading = ref(false)

const route = useRoute()
const router = useRouter()
const notify = useNotification()

const headers = ref()

const formInitValue = {
  title: null,
  ticket_source_id: null,
  content: null,
  create_msg: null,
  ticket_attachments: []
}
const formValue = ref(cloneDeep(formInitValue))
const formRules = {
  title: [
    { required: true, message: '事件名称不可为空' },
    { maxLength: 40, message: '事件名称最大长度不易超过 40 字符' }
  ],
  ticket_source_id: [
    { required: true, message: '事件来源不可为空' }
  ],
  content: [
    { required: true, message: '用户账号不可为空' }
  ]
}

const { data, isFetching } = useQuery({
  query: gql`
    query {
      ticket_source {
        id
        content
      }
    }
  `
})

watch(
  () => isFetching.value,
  isFetched => {
    if (isFetched) {
      headers.value = getHeaders()
    }
  }, { immediate: true }
)

const sourceOptions = computed(() => {
  const { ticket_source } = data.value || {}

  if (Array.isArray(ticket_source)) {
    return ticket_source.map(({ id, content }) => ({
      name: content,
      value: id
    }))
  }

  return []
})

function handleConfirm() {
  if (formRef.value?.handleSubmit) {
    formRef.value?.handleSubmit()
  }
}

function handleSubmit({ values: rawValues, errors }) {
  if (errors) return

  const {
    ticket_attachments = [],
    ...values
  } = rawValues

  if (Array.isArray(ticket_attachments)) {
    values.ticket_attachments = []
    ticket_attachments.forEach(({ response: { code, data } }) => {
      if (code === 0 && data?.id) {
        values.ticket_attachments.push(data.id)
      }
    })
  }

  for (let key in values) {
    if (isNil(values[key])) {
      delete values[key]
    }
  }

  useApi()
    .post('ticket', values, { authorize: true })
    .then(res => {
      if (res.code === 0) {
        notify.success({
          content: '事件录入成功',
          meta: '即将跳到列表页',
          duration: 5e3,
          onAfterEnter: back
        })
      }
    })
}

function back() {
  router.push({ name: 'Ticket' })
}
</script>